//
//  BeanObj.m
//  storeapp
//
//  Created by huangyi on 13-4-17.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "BeanObject.h"
#import "Bean.h"

#import "NSArray+utils.h"
#import "NSData+encode.h"
#import "NSString+encode.h"
#import "NSString+utils.h"

#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "FMDatabasePool.h"
#import "FMDatabaseQueue.h"

#define RowToAdd NSIntegerMin

@interface BeanObject ()

-(void)setId:(int)rowid;

@end

@implementation BeanObject

-(id)init{
    self=[super init];
    if (self) {
        self.bean=[NSMutableDictionary dictionary];
    }
    return self;
}

-(int)store{
    int rowid=[self getId];
    NSString *tableName=self.table.tableName;
    [self createTable:tableName];
    [self alterTable];
    FMDatabase *db=[self.table.db getFMDB];
    if (rowid!=RowToAdd) {
        NSMutableArray *sql=[NSMutableArray array];
        NSArray *keys=self.bean.allKeys;
        for (NSString *key in keys) {
            if (![key isEqualToString:@"id"]) {
                NSString *value=self.bean[key];
                [sql addObject:[NSString stringWithFormat:@"%@='%@'",key,value]];
            }
        }
        if (keys.count) {
            NSString *str=[NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE id=%i",tableName,[sql componentsJoinedByString:@","],rowid];
            [db executeUpdate:str];
        }
    }else{
        NSArray *keys=self.bean.allKeys;
        if (keys.count) {
            NSArray *values=self.bean.allValues;
            NSString *str=[NSString stringWithFormat:@"INSERT INTO %@ (%@) VALUES('%@')",tableName,[keys componentsJoinedByString:@","],[values componentsJoinedByString:@"','"]];
            if ([db executeUpdate:str]) {
                rowid=[db lastInsertRowId];
                [self setId:rowid];
            }
        }
    }
    rowid=[self getId];
    return rowid;
}
-(BOOL)trash{
    BOOL result=YES;
    int rowid=[self getId];
    if (rowid!=RowToAdd) {
        NSString *tableName=self.table.tableName;
        FMDatabase *db=[self.table.db getFMDB];
        NSString *sqlstr=[NSString stringWithFormat:@"DELETE FROM %@ WHERE id=%i",tableName,rowid];
        result=[db executeUpdate:sqlstr];
    }
    return result;
}
-(NSDictionary*)dump{
    return [NSDictionary dictionaryWithDictionary:self.bean];
}

-(int)getId{
    int rowid=RowToAdd;
    NSNumber *number=self.bean[@"id"];
    if (number!=nil) {
        rowid=number.intValue;
    }
    return rowid;
}
-(void)setId:(int)rowid{
    [self setValue:@(rowid) forField:@"id"];
}

-(NSString*)getString:(NSString*)field{
    NSString *str=self.bean[field];
    return str;
}
-(NSNumber*)getNumber:(NSString*)field{
    NSNumber *num=self.bean[field];
    return num;
}
-(NSData*)getData:(NSString*)field{
    NSString *b64=self.bean[field];
    return b64.base64decode;
}
-(NSDate*)getDate:(NSString*)field{
    NSNumber *ts=self.bean[field];
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:ts.doubleValue];
    return date;
}

-(void)setValue:(id)value forField:(NSString*)field{
    id result=nil;
    if ([value isKindOfClass:[NSNumber class]]) {
        result=value;
    }
    if ([value isKindOfClass:[NSString class]]) {
        result=value;
    }
    if ([value isKindOfClass:[NSData class]]) {
        NSData *b64=value;
        result=b64.base64;
    }
    if ([value isKindOfClass:[NSDate class]]) {
        NSDate *date=value;
        NSTimeInterval ts=date.timeIntervalSince1970;
        result=@(ts);
    }
    self.bean[field]=result;
}
-(void)convert:(NSDictionary*)dictionary{
    [self.bean setValuesForKeysWithDictionary:dictionary];
}

-(BOOL)alterTable{
    FMDatabase *db=[self.table.db getFMDB];
    NSString *tableName=self.table.tableName;
    NSArray *fields=[self.table getFieldNames];
    NSArray *keys=self.bean.allKeys;
    NSMutableArray *sql=[NSMutableArray array];
    for (NSString *key in keys) {
        if (![fields containsString:key]) {
            id value=self.bean[key];
            NSString *type=@"TEXT";
            if ([value isKindOfClass:[NSNumber class]]) {
                type=@"REAL";
            }
            if ([value isKindOfClass:[NSDate class]]) {
                type=@"REAL";
            }
            [sql addObject:[NSString stringWithFormat:@"ALTER TABLE %@ ADD '%@' %@",tableName,key,type]];
        }
    }
    BOOL result=YES;
    if (sql.count) {
        result=[db executeUpdate:[sql componentsJoinedByString:@";"]];
    }
    return result;
}

-(BOOL)createTable:(NSString*)tablename{
    NSString *sql=[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('id' INTEGER PRIMARY KEY AUTOINCREMENT)",tablename];
    FMDatabase *db=[self.table.db getFMDB];
    BOOL result=[db executeUpdate:sql];
    return result;
}



@end
